package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.entity.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.entity.vo.AttrRespVo;
import com.atguigu.gulimall.product.entity.vo.AttrVO;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.service.ProductAttrValueService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationService attrgroupRelationService;

    @Autowired
    private AttrAttrgroupRelationDao attrgroupRelationDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public PageUtils queryPageBtCatId(Map<String, Object> params, Long catId,String type) {
        //base 基础属性 sale销售属性
        int attrType = "base".equalsIgnoreCase(type) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode();
                QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type" ,attrType);
        //分类id
        if (catId != 0){
            queryWrapper.eq("catelog_id",catId);
        }

        //搜索关键字
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper)->{
                wrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<Object> attrResps = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity,attrRespVo);

            //基础属性才有分组信息
            if (attrType == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
                //获取属性分组名称
                AttrAttrgroupRelationEntity relationEntity = attrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId()));
                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                    Long attrGroupId = relationEntity.getAttrGroupId();
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }

            //获取属性分类名称
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null){
                attrRespVo.setCatelogName(categoryEntity.getName());
            }

            return attrRespVo;
        }).collect(Collectors.toList());

        // 设置最新数据
        pageUtils.setList(attrResps);

        return pageUtils;
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        //查询组关联的属性Id列表
        List<AttrAttrgroupRelationEntity> attrGroups = attrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        List<Long> attrIds = attrGroups.stream().map((attr) -> {
            Long attrId = attr.getAttrId();
            return attrId;
        }).collect(Collectors.toList());

        //如果组没有关联任何属性，直接返回null
        if (attrIds == null || attrIds.size() == 0){
            return null;
        }

        //如果有关联，根据id查询关联的属性数据
        List<AttrEntity> attrEntities = this.listByIds(attrIds);
        return attrEntities;
    }

    @Override
    public PageUtils getNoRelationAttr(Long attrGroupId,Map<String, Object> params) {
        //根据组id查询分组信息
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);

        //获取组所属的分类
        Long catelogId = attrGroupEntity.getCatelogId();

        //获取这个分类下所有分组
        List<AttrGroupEntity> catelogAttrGroups = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> collect = catelogAttrGroups.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());


        //在中间表获取这个分类下其他分组关联的属性
        List<AttrAttrgroupRelationEntity> attrgroupRelations = attrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
        List<Long> attrIds = attrgroupRelations.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //排除已经关联过的属性，查询可关联的属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (attrIds != null && attrIds.size() > 0){
            wrapper.notIn("attr_id", attrIds);
        }
        //添加搜索分页条件
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((obj)->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);

    }

    @Override
    public List<ProductAttrValueEntity> listforspu(Long spuId) {

        List<ProductAttrValueEntity> valueEntities = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));

        return valueEntities;
    }

    @Transactional
    @Override
    public void updatespuattr(Long spuId, List<ProductAttrValueEntity> entitys) {
        //先删除，再重新保存
        productAttrValueService.remove(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id",spuId));

        List<ProductAttrValueEntity> collect = entitys.stream().map(item -> {
            item.setSpuId(spuId);
            return item;
        }).collect(Collectors.toList());

        productAttrValueService.saveBatch(collect);
    }

    @Override
    public List<Long> getSearchAttrIds(List<Long> attrids) {

        return this.baseMapper.getSearchAttrIds(attrids);
    }


    @Override
    @Transactional
    public void saveAttr(AttrVO attr) {
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attr,entity);
        //保存自己的属性
        this.save(entity);

        //基础属性才有分组信息
        if (entity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            //保存属性和属性组的关系
            attrgroupRelationService.saveAttrGroup(attr.getAttrGroupId(), entity.getAttrId());
        }
    }

    @Cacheable(value = "attr",key = "'attrinfo'+#root.args[0]")
    @Override
    public AttrRespVo getAttrDetail(Long attrId) {
        //查询基础数据
        AttrRespVo respVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,respVo);

        //基础属性才有分组信息
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //查询分组信息
            AttrAttrgroupRelationEntity relationEntity = attrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationEntity != null){
                Long attrGroupId = relationEntity.getAttrGroupId();
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                if (attrGroupEntity != null){
                    respVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    respVo.setAttrGroupId(attrGroupEntity.getAttrGroupId());
                }
            }
        }

        //查询分类路径
        Long[] catelogPath = categoryService.getCatelogPath(attrEntity.getCatelogId());
        respVo.setCatelogPath(catelogPath);

        return respVo;
    }

    @Override
    public void updateAttrById(AttrVO attr) {
        //先更新属性基本信息
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attr,entity);
        this.updateById(entity);

        //基础属性才有分组信息
        if (entity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //更新属性分组信息
            Long attrGroupId = attr.getAttrGroupId();
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attrGroupId);
            relationEntity.setAttrId(attr.getAttrId());

            List<AttrAttrgroupRelationEntity> attrId = attrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            //如果属性和分组有关系做跟新，没有关系做新增操作
            if (attrId.size() > 0){
                attrgroupRelationDao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
            }else {
                attrgroupRelationDao.insert(relationEntity);
            }
        }
    }


}